package yunjiao.javatutorials.guava.concurrent.transform.assembly;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.Arrays;
import java.util.concurrent.Executors;

/**
 * 电商订单处理流水线
 *
 * @author yangyunjiao
 */
public class OrderProcessingService {
    private final ListeningExecutorService executor =
            MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));

    /**
     * 完整的订单处理流水线
     */
    public ListenableFuture<OrderResult> processOrderAsync(String orderId) {
        System.out.println(">>>完整的订单处理流水线：获取订单基本信息 -> 验证订单有效性 -> 检查库存（异步操作） -> 计算价格 -> 最终处理结果");

        // 1. 获取订单基本信息
        ListenableFuture<OrderInfo> orderInfoFuture = getOrderInfoAsync(orderId);

        // 2. 验证订单有效性
        ListenableFuture<ValidatedOrder> validatedFuture = Futures.transform(
                orderInfoFuture,
                this::validateOrder,
                executor
        );

        // 3. 检查库存（异步操作）
        ListenableFuture<InventoryCheck> inventoryFuture = Futures.transformAsync(
                validatedFuture,
                this::checkInventoryAsync,
                executor
        );

        // 4. 计算价格
        ListenableFuture<PriceCalculation> priceFuture = Futures.transform(
                inventoryFuture,
                this::calculatePrice,
                executor
        );

        // 5. 最终处理结果
        return Futures.transform(
                priceFuture,
                this::generateOrderResult,
                executor
        );
    }

    // 各个处理阶段的方法实现
    private ListenableFuture<OrderInfo> getOrderInfoAsync(String orderId) {
        System.out.println("getOrderInfoAsync");
        return executor.submit(() -> {
            // 模拟数据库查询
            Thread.sleep(100);
            return new OrderInfo(orderId, "user123", Arrays.asList("item1", "item2"));
        });
    }

    private ValidatedOrder validateOrder(OrderInfo orderInfo) {
        System.out.println("validateOrder");
        if (orderInfo.items().isEmpty()) {
            throw new ValidationException("订单不能为空");
        }
        return new ValidatedOrder(orderInfo, true, "验证通过");
    }

    private ListenableFuture<InventoryCheck> checkInventoryAsync(ValidatedOrder order) {
        System.out.println("checkInventoryAsync");
        return executor.submit(() -> {
            // 模拟库存检查服务调用
            Thread.sleep(150);
            boolean allAvailable = order.orderInfo().items()
                    .stream().allMatch(item -> Math.random() > 0.1); // 90%概率有库存
            return new InventoryCheck(order, allAvailable);
        });
    }

    private PriceCalculation calculatePrice(InventoryCheck check) {
        System.out.println("calculatePrice");
        if (!check.allAvailable()) {
            throw new InventoryException("部分商品库存不足");
        }

        double total = check.validatedOrder().orderInfo().items().size() * 25.0;
        return new PriceCalculation(check, total, total * 0.1); // 10%折扣
    }

    private OrderResult generateOrderResult(PriceCalculation calculation) {
        System.out.println("generateOrderResult");
        return new OrderResult(
                calculation.inventoryCheck().validatedOrder().orderInfo().orderId(),
                "SUCCESS",
                calculation.totalPrice(),
                calculation.discount()
        );
    }


}
